//
//  PDFPagePickerGridViewCell.m
//  Cachalot
//
//  Created by Adam Cue on 6/30/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PDFPagePickerGridViewCell.h"

@interface PDFPagePickerGridViewCell (Private)
#pragma mark SetupMethods
- (void)setupPageView;
- (void)setupAnnotationView;
- (void)setupCountLabel;
@end

@implementation PDFPagePickerGridViewCell

@synthesize pageView = _pageView;
@synthesize annotationView = _annotationView;
@synthesize countLabel = _countLabel;
@synthesize superViewController;

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier 
superViewController:(UIViewController <PDFPagePreviewViewDelegate> *)vc{
  self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier];
  if(self){
     self.backgroundColor = [UIColor clearColor];
     self.contentView.backgroundColor = [UIColor clearColor];
     self.superViewController = vc;
     [self setupPageView];
     [self setupAnnotationView];
     [self setupCountLabel];
  }
  return self;
}

#pragma mark SetupMethods
- (void)setupPageView{
   _pageView = [[PDFPagePreviewView alloc] initWithFrame:CGRectMake(3, 4, 96, 128) index:0];
   self.pageView.backgroundColor = [UIColor clearColor];
   self.pageView.contentMode = UIViewContentModeScaleAspectFit;
   self.pageView.delegate = self.superViewController;
   [self.contentView addSubview:self.pageView];
}

- (void) setupAnnotationView{
   _annotationView = [[UIImageView alloc] initWithFrame:self.pageView.frame];
   self.annotationView.backgroundColor = [UIColor clearColor];
   self.annotationView.contentMode = UIViewContentModeScaleAspectFit;
   [self.contentView addSubview:self.annotationView];
}

- (void) setupCountLabel{
   _countLabel = [[UILabel alloc] initWithFrame:CGRectMake(3, 56, 96, 24)];
   self.countLabel.backgroundColor = [UIColor clearColor];
   self.countLabel.textColor = [UIColor blackColor];
   self.countLabel.textAlignment = UITextAlignmentCenter;
   self.countLabel.font = [UIFont systemFontOfSize:24];
   [self.contentView addSubview:self.countLabel];
}

#pragma mark ExternalMethods
+ (void)fillCell:(PDFPagePickerGridViewCell *)cell forAnnotationView:(AnnotationView *)annotationView andPage:(UIImage *)page andCount:(NSInteger)count {
   cell.pageView.backgroundColor = [UIColor whiteColor];
   cell.pageView.index = count-1;
   UIGraphicsBeginImageContext(annotationView.frame.size);
	[annotationView.layer renderInContext:UIGraphicsGetCurrentContext()];
	UIImage *annotationViewImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
   cell.pageView.image = page;
   cell.annotationView.image = annotationViewImage;
   cell.countLabel.text = [NSString stringWithFormat:@"%d", count];
}

@end
